<template>
<div class="order-detail">
    <div class="order-wrap h-fix-btn">
        <!-- 待支付 -->
        <div v-if='data.statusInfo == 1' v-cloak class="m-pay floor">
            <h4 class="m-status">待支付</h4>
            <span class="qrcode qrcode-fr" @click="qrcodeAlert(data.orderId)"></span>
            <div class="m-cont">
                <p>请在<span class="g-time">{{ data.cancelLeftTime }}</span>内完成支付，超时后会自动取消。</p>
            </div>
        </div>
        <!-- 待配送、待收货 -->
        <div v-if='data.statusInfo == 2 || data.statusInfo == 3' v-cloak class="m-delivery floor">
            <h4 class="m-status" v-text="data.statusName"></h4>
            <span class="qrcode qrcode-fr" @click="qrcodeAlert(data.orderId)"></span>
            <a :href="'/#/orderTrail/' + orderid">
                <div class="m-cont">
                    <p>{{ data.isPickUp == '0' ? '预计送达时间为' : '自提时间为' }} <span class="g-time">{{data.expressTime}}</span></p>
                    <p class="g-track">订单跟踪：{{ data.nearTrailInfo.serialDesc }}
                        <i class="c-back"></i>
                    </p>
                </div>
            </a>
        </div>
        <!-- 交易完成  -->
        <div v-if='data.statusInfo == 0' v-cloak class="m-finish floor">
            <h4 class="m-status">交易完成</h4>
             <span class="qrcode qrcode-fr" @click="qrcodeAlert(data.orderId)"></span>
            <a :href="'/#/orderTrail/' + orderid">
                <div class="m-cont">
                    <p>成交时间：{{ data.receiptTime }}</p>
                    <p class="g-track">订单跟踪：{{ data.nearTrailInfo.serialDesc }}
                        <i class="c-back">111</i>
                    </p>
                </div>
            </a>
        </div>
        <!-- 交易取消 -->
        <div v-if='data.statusInfo == 4' v-cloak class="m-cancel floor">
            <h4 class="m-status">交易取消</h4>
            <span class="qrcode qrcode-fr" @click="qrcodeAlert(data.orderId)"></span>
            <a :href="'/#/orderTrail/' + orderid">
                <div class="m-cont">
                    <p class="g-track">订单跟踪：{{ data.nearTrailInfo.serialDesc }}
                        <i class="c-back"></i>
                    </p>
                </div>
            </a>
        </div>

        <!-- 退货状态：判断退货商品(returnItems)是否为空 -->
        <div v-show='data.returnItems.length > 0 || data.refundStep' v-cloak class="o-pro-status floor" v-cloak>
            <div v-if="data.refundStep == 00" class="o-status-mess">
                <h4 class="m-status">退款申请已提交</h4>
                <div class="m-statusTxt">
                    <p>退款金额：<span class="goods-price">&yen;{{ data.refundMoney }}</span> (预计1-15个工作日退至支付账户)</p>
                    <p>申请时间：{{ data.refundTime }}</p>
                </div>
            </div>

            <div v-else class="o-status-mess">
                <h4 class="m-status">退款已完成</h4>
                <span class="qrcode qrcode-fr" @click="qrcodeAlert(data.orderId)"></span>
                <div class="m-statusTxt">
                    <p>退款金额：<span class="goods-price">&yen;{{ data.refundMoney }}</span> (预计1-15个工作日退至支付账户)</p>
                    <p>退款时间：{{ data.refundFinishTime }}</p>
                    <p>申请时间：{{ data.refundTime }}</p>
                </div>
            </div>


            <div v-for="item in data.returnItems" class="m-cont o-list-con clearfix item-wide">
                <div class="o-index-pro-pic">
                    <img :src="item.imgSrc" :alt="item.commdtyName" @error.once="imgError">
                </div>
                <div class="o-pro-info">
                    <span class="o-pro-tit">{{ item.commdtyName }}</span>
                    <i v-if="item.itemStatus == '08'" v-cloak class="o-pro-num">全部拒收</i>
                    <i v-else class="o-pro-num" v-cloak>已拒收<span>{{ item.returnQty }}</span>件</i>
                </div>
                <div class="qa-price clearfix">
                    <div class="price-text">
                        <span class="goods-price">&yen;{{ item.price }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 送货地址（完成、待支付，配送中、取消）|| 自提信息 -->
        <div v-if="data.isPickUp == '0'" v-cloak class="delivery floor">
            <h4 class="m-title">
                <span class="order-ico deli-icon">送货地址</span>
            </h4>
            <div class="m-cont">
                <p>{{ data.receiverInfo.receiveName }}   {{ telEncode(data.receiverInfo.receiveTel) }}</p>
                <p>{{ data.receiverInfo.provinceName }}{{ data.receiverInfo.cityName }}{{ data.receiverInfo.districtName }}{{ data.receiverInfo.interestPointName }}{{ data.receiverInfo.detailAddress }}</p>
            </div>
        </div>
        <div v-else v-cloak class="delivery floor delivery-info">
            <h4 class="m-title">
                <a href="javascript:void(0);" class="pickup-process-btn" @click="showPickupProcess = true"></a>
                <span class="order-ico deli-icon">自提信息</span>
            </h4>
            <div class="delivery-info-content">
                <p>{{ data.pickUpInfoVO.receiveName }}   {{ telEncode(data.pickUpInfoVO.receiveTel) }}</p>
                <p><span>自提地址：</span> {{ data.pickUpInfoVO.pickUpAddress }}</p>
                <p><span>门店电话：</span> {{ data.pickUpInfoVO.pickUpPhone }}</p>
                <p><span>自提时间：</span> {{ data.expressTime }}</p>
            </div>
        </div>
        <!-- 买家留言1待支付、2待配送、3配送中 -->
        <div v-if="data.remarkInfo" v-show='data.statusInfo == 1 || data.statusInfo == 2 || data.statusInfo == 3' v-cloak class="delivery floor">
            <h4 class="m-title">
                <span class="order-ico mess-ico">买家留言</span>
            </h4>
            <div v-cloak class="m-cont">
                <p v-if="data.remarkInfo">{{ data.remarkInfo }}</p>
                <p v-else>无</p>
            </div>
        </div>

        <!-- 商品清单（完成、待支付，配送中） -->
        <div v-show='data.orderItems.length > 0' v-cloak class="delivery floor">
            <h4 class="m-title">
                <span class="order-ico defu-ico">
                    &nbsp;
                    <!--{{data.storeName}}-->
                </span>
            </h4>

            <div v-for="item in data.orderItems" class="m-cont o-list-con clearfix item-wide">
                <a :href="`/#/detail/${item.commdtyCode}/0000000000`">
                    <div class="o-index-pro-pic">
                        <img :src="item.imgSrc" :alt="item.commdtyName" @error.once="imgError">
                    </div>
                    <div class="o-pro-info pr">
                        <span class="o-pro-tit">{{ item.commdtyName }}</span>
                        <i class="o-pro-num">x{{ item.quantity }}</i>
                    </div>
                    <div class="qa-price clearfix">
                        <div class="price-text">
                            <span class="goods-price">&yen;{{ item.price }}</span>
                        </div>
                    </div>
                    <div v-if="item.unpickQty>0" class="o-status">
                        <span>缺货</span>{{item.unpickQty}}件未配送
                    </div>
                </a>
            </div>

            <div class="m-cont o-pro-price">
                <ul>
                    <li><span class="p-teb-name">商品总额：</span><span class="p-teb-cont">&yen;{{ data.orderAmount }}</span></li>
                    <li><span class="p-teb-name">配送费：</span><span class="p-teb-cont">&yen;{{ data.shipChargeAmt}}</span></li>
                    <li v-if="parseFloat(data.orderPromotionAmt)"><span class="p-teb-name">订单优惠：</span><span class="p-teb-cont">- &yen;{{ data.orderPromotionAmt}}</span></li>
                    <li v-if="parseFloat(data.couponAmt)"><span class="p-teb-name">优惠券：</span><span class="p-teb-cont">-&yen;{{ data.couponAmt}}</span></li>

                    <li v-show="data.payTypeDesc.length > 0"><span class="p-teb-name">支付方式：</span><span class="p-teb-cont">{{ data.payTypeDesc }}</span></li>
                    <li v-show="data.payAmt.length > 0"><span class="p-teb-name sfze">实付总额：</span><span class="p-teb-cont p-reds">&yen;{{ data.payAmt }}</span></li>

                </ul>
            </div>
        </div>
        <!-- 订单号（完成、待支付，配送中、取消） -->
        <div v-cloak class="delivery floor">
            <div class="m-cont o-order-mess">
                <ul>
                    <li><span class="p-teb-name">订单号：</span><span class="p-teb-cont">{{ data.orderId }}</span></li>
                    <li><span class="p-teb-name">下单时间：</span><span class="p-teb-cont">{{ data.orderTime }}</span></li>

                    <li v-show="data.payTime && data.payTime.length > 0"><span class="p-teb-name">支付时间：</span><span class="p-teb-cont">{{ data.payTime }}</span></li>
                    <li v-show="data.expressTime.length > 0 && data.isPickUp == '0'">
                        <span class="p-teb-name">送达时间：</span>
                        <span v-if="data.statusInfo == '00' || data.status == '08'" class="p-teb-cont">{{ data.receiptTime }}</span>
                        <span v-else class="p-teb-cont">预计{{ data.expressTime }}</span>
                    </li>
                    <li v-if="data.isPickUp == '1' && data.expressTime">
                        <span class="p-teb-name">自提时间：</span>
                        <span class="p-teb-cont" v-text="`预计${data.expressTime}`"></span>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- 待支付 -->
    <div v-if='data.statusInfo == 1' v-cloak class="btn-bottom">
        <div class="o-btn">
            <a class="cancelOrderBtn" href="javascript:;" @click="cancelOrder()">取消订单</a>
            <a class="go-pay" :href="'/#/cart3/' + data.orderId + '?form=orderdetail'">去支付</a>
        </div>
    </div>

    <!-- 待配送 -->
    <div v-if='data.statusInfo == 2' v-cloak class="btn-bottom">
        <div class="o-btn" v-bind:class="{'btn-num2': data.showReminder == 1}">
            <a v-if='data.status != "05" && data.orderType!=2' class="cancelOrderBtn" href="javascript:;" @click="cancelOrder()">取消订单</a>
            <!-- 联系微仓主 -->
            <a v-if="data.showReminder == 1" href="javascript:;" @click="reminder(data.wcOwnerTel)">催单</a>
        </div>
    </div>

    <!-- 配送中 -->
    <div v-if='data.statusInfo == 3' v-cloak class="btn-bottom">
        <div class="o-btn">
            <a :href="'tel:' + data.courierTel">联系快递员</a>
        </div>
    </div>

    <!-- 交易完成 -->
    <!-- <div v-if='data.statusInfo == 0' v-cloak class="btn-bottom">
        <div class="o-btn o-btn-call btn-num1">
            <a href="">再次购买</a>
        </div>
    </div> -->

    <!-- 已取消 -->
    <div v-if="data.statusInfo == 4 && data.payTime" v-cloak class="btn-bottom">
        <div class="o-btn">
            <a class="deleteOrderBtn" href="javascript:;" @click="delOrder">删除订单</a>
        </div>
    </div>

    <!-- 全部拒收 -->
    <div v-if="data.status == '08'" v-cloak class="btn-bottom">
        <div class="o-btn">
            <a class="deleteOrderBtn" href="javascript:;" @click="delOrder">删除订单</a>
        </div>
    </div>

    <!-- 自提流程图 -->
    <div class="pickup-process" v-show="showPickupProcess">
        <div class="image">
            <i @click="showPickupProcess = false"></i><span></span>
        </div>
    </div>
    <div class="alertCode-container" v-show="alertCode">
      <div class="code-bg">
        <div id="qrcode"></div>
        <i @click="alertCode=false"></i>
        <span></span>
      </div>
    </div>
</div>
</template>

<script>
import fetch from '../../config/fetch';
import * as domains from '../../config/env';
import * as Util from '../../config/utils';
import { statusInfo } from './statusInfo';
import QRCode from './QRCode.js'

export default {
    data () {
        return {
            orderid: this.$route.params.orderid,
            showPickupProcess: false,
            alertCode: false,
            data: {
                receiverInfo: {},
                orderItems: [],
                returnItems: [],
                payTime: '',
                expressTime: '',
                payTypeDesc: '',
                payAmt: '',
                isPickUp: '0',
                pickUpInfoVO: {}
            }
        }
    },
    mounted () {
        this.getOrderDetail();
    },
    methods: {
       qrcodeAlert (orderId) {
        this.alertCode = true ;
        $('#qrcode img').remove();
        new QRCode(document.getElementById("qrcode"), {
          text: orderId,
          width: 200,
          height: 200,
          colorDark : "#000000",
          colorLight : "#ffffff",
          correctLevel : QRCode.CorrectLevel.H
        });
      },
        /* 取订单详情数据 */
        getOrderDetail() {
            let that = this;
            $.ajax({
                url: domains.tps + '/app/orderCenter/showOrderDetail.do',
                data: {
                    app: 'wap',
                    appVersion: '3.2.2',
                    orderId: this.orderid
                },
                dataType: 'jsonp',
                jsonp: 'callBack',
                jsonpCallback: 'getOrderDetail',
                success: function(res){
                    if (res && res.data) {
                        let data = res.data;

                        //获取退货列表图片
                        data.returnItems.length && $.each(data.returnItems, function(i, v){
                            v.imgSrc = that.getImgURL(v.imgFlag, v.commdtyCode);
                        })
                        //获取商品列表图片
                        data.orderItems.length && $.each(data.orderItems,function(i,v){
                            v.imgSrc = that.getImgURL(v.imgFlag, v.commdtyCode);
                        })
                        data.receiverInfo.receiveTel = Util.getTelReplace(data.receiverInfo.receiveTel);

                        data.refundMoney = parseFloat(data.refundMoney).toFixed(2);

                        // 修改数据模型
                        that.data = data;

                        // 根据状态码查找文案
                        $.each(statusInfo[data.isPickUp == '1' ? 'pickUp' : 'delivery'], function(si, sv){
                            if (sv.data.indexOf(data.status) >= 0) {
                                that.data.statusInfo = si;
                                that.data.statusName = sv.name;
                            };
                        });

                        that.countDown();
                    }
                },
                error: function() {
                    AlertBox({type: "mini", msg: "网络异常，请稍后再试"});
                }
            });
        },

        /* 组装图片URL */
        getImgURL(flag, code) {
            var self = this;
            if (flag == '0') {
                return domains.img() + '/uimg/b2c/newcatentries/00000000-' + code +'_1_200x200.jpg';
            }
            else {
                return domains.img() + '/uimg/cmws/catentries/' + code + '_1_200x200.jpg';
            }
        },

        /* 取消订单 */
        cancelOrder() {
            let that = this;

            AlertBox({type:'doubleBtn',alertType:'fixed',title:'好货不等人，客官再考虑下呗',cancelText:'容我三思',confirmText:'我意已决',confirm:function(){
				$.ajax({
				  	type: 'POST',
				  	url: domains.tps + '/app/orderCenter/cancelOrder.do',
				  	data: {
                        orderId: that.orderid
                    },
				  	dataType: 'json',
					beforeSend: function(xhr) {
                        xhr.withCredentials = true;
                    },
					success: function(data){
                        if(data.code==1){
                            location.href = "/#/orders";
                        }else{
                            AlertBox({type: "mini", msg: data.msg});
                        }
                        
					},
					error: function(xhr, type){
					    AlertBox({type: "mini", msg: "网络异常，请稍后再试"});
					}
				});
			}});
        },

        /* 删除订单 */
        delOrder() {
            let that = this;

            AlertBox({type:'doubleBtn',alertType:'fixed',title:'删除订单后无法找回，确认继续？',confirm:function(){
				$.ajax({
				  	type: 'POST',
				  	url: domains.tps + '/app/orderCenter/deleteOrder.do',
				  	data: {
                        app: 'wap',
                        orderId: that.orderid
                    },
				  	dataType: 'json',
					beforeSend: function(xhr) {
                        xhr.withCredentials = true;
                    },
					success: function(data){
						location.href = "/#/orders";
					},
					error: function(xhr, type){
					    AlertBox({type: "mini", msg: "网络异常，请稍后再试"});
					}
				});
			}});
        },

        /* 催单 */
        reminder(tel) {
            AlertBox({
                type:'doubleBtn',
                alertType:'fixed',
                title:'已通知苏鲜生店尽快为您配送，请耐心等待一会儿~',
                confirmText: "我再等等",
                cancelText: "联系苏鲜生",
                cancel:function(){
                    location.href = "tel:"+tel;
                }
            })
        },

        /* 倒计时 */
        countDown() {
            if (!this.data.cancelLeftTime) {
                return;
            }

            let parts = this.data.cancelLeftTime.replace(/小时|分|秒/g, '-').split('-'),
                seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + parseInt(parts[2]);

            setInterval(() => {
                if (!seconds) {
                    return;
                }
                seconds--;

                let h = parseInt(seconds / 60 / 60, 10);
                let m = parseInt(seconds / 60 % 60, 10);
                let s = parseInt(seconds % 60, 10);

                if (h < 10) h = '0' + h;
                if (m < 10) m = '0' + m;
                if (s < 10) s = '0' + s;

                this.data.cancelLeftTime = h + '小时' + m + '分' + s + '秒';
            }, 1000);
        },

        imgError(event) {
            event.target.src = '/static/images/pro-default.png';
        },

        telEncode(tel) {
            return Util.getTelReplace(tel);
        }


    },
    components: {

    }
    ,beforeRouteLeave (to, from, next, redirect) {
		if(to.path == 'cart3'){
            next(false)
            router.push('/orders')
        }else{
            next(true)
        }
	}
}
</script>

<style lang="scss" scoped>
@import "./style";
</style>
